package com.anji.plus.gaea.inf.intercepter;

import com.anji.plus.gaea.inf.constant.InfConstant;
import com.anji.plus.gaea.inf.constant.ResEnum;
import com.anji.plus.gaea.inf.exception.InfException;
import com.anji.plus.gaea.inf.extension.GaeaInfHepler;
import com.anji.plus.gaea.inf.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ultrajiaming
 * @since 2021/3/19 12:50
 * 校验app secret
 */
public class AppSecretInterceptor implements HandlerInterceptor {

    public static final String URL = "/custom/dynamic/execute";

    @Autowired
    private GaeaInfHepler gaeaInfHepler;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        // 校验appId、appSecret
        if (StrUtil.containsIgnoreCase(requestURI, URL)) {
            String appId = request.getHeader(InfConstant.REQUEST_HEADER_APP_ID);
            String appSecret = request.getHeader(InfConstant.REQUEST_HEADER_APP_SECRET);
            if (StringUtils.isBlank(appId) || StringUtils.isBlank(appSecret)) {
                throw InfException.code(ResEnum.APP_SECRET_NOT_NULL.getCode());
            }
            if (!gaeaInfHepler.checkAppIdSecret(appId, appSecret)) {
                throw InfException.code(ResEnum.SECRET_AUTHENTICATED_FAIL.getCode());
            }

            // 校验是否授权


            return true;
        }
        return true;
    }

}
